package com.dsp.inventory.service.impl;

import com.dsp.inventory.dao.InventoryDao;
import com.dsp.inventory.dto.InventoryDTO;
import com.dsp.inventory.entity.Inventory;
import com.dsp.inventory.service.InventoryService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.dromara.hmily.common.exception.HmilyRuntimeException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class InventoryServiceImpl implements InventoryService {

    @Resource
    private InventoryDao inventoryDao;

    public List<Inventory> findAll(){
        return (List<Inventory>) inventoryDao.findAll();
    }

    @HmilyTCC(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod")
    @Transactional(rollbackFor = Exception.class)
    public Boolean decrease(InventoryDTO inventoryDTO) {
        log.info("减库存...开始:{},num:{}",inventoryDTO.getId(),inventoryDTO.getNum());
        return inventoryDao.decrease(inventoryDTO.getId(), inventoryDTO.getNum());
    }

    @HmilyTCC(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod")
    @Transactional(rollbackFor = Exception.class)
    public Boolean decreaseException(InventoryDTO inventoryDTO) {
        log.info("减库存...开始:{},num:{}",inventoryDTO.getId(),inventoryDTO.getNum());
        throw new HmilyRuntimeException("减库存异常:"+inventoryDTO.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmMethod(InventoryDTO inventoryDTO) {
        log.info("减库存...确认:{}...num:{}",inventoryDTO.getId(),inventoryDTO.getNum());
        final int decrease = inventoryDao.confirm(inventoryDTO.getId(),inventoryDTO.getNum());
        if (decrease != 1) {
            throw new HmilyRuntimeException("库存确认异常:"+inventoryDTO.getId());
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelMethod(InventoryDTO inventoryDTO) {
        log.info("减库存...恢复:{}...num:{}",inventoryDTO.getId(),inventoryDTO.getNum());
        final int decrease = inventoryDao.cancel(inventoryDTO.getId(),inventoryDTO.getNum());
        if (decrease != 1) {
            throw new HmilyRuntimeException("库存恢复异常:"+inventoryDTO.getId());
        }
        return true;
    }
}
